package com.example.gobang.controller;

import com.example.gobang.model.MatchRequest;
import com.example.gobang.model.MatchResponse;
import com.example.gobang.game.Matcher;
import com.example.gobang.game.OnlineUserManager;
import com.example.gobang.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
// 处理匹配功能中的websocket请求
@Component
@Slf4j
public class MatchController extends TextWebSocketHandler {
    @Autowired
    public ObjectMapper objectMapper;
    @Autowired
    public OnlineUserManager userManager;
    @Autowired
    private Matcher matcher;
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 玩家上线
        try {
            User user = (User) session.getAttributes().get("user");
            WebSocketSession online = userManager.getOnline(user.getUserId());
            WebSocketSession onlineRoom = userManager.getOnlineRoom(user.getUserId());
            if(online != null || onlineRoom != null){
                // 说明已经登录
                MatchResponse response = new MatchResponse();
                response.setOk(true);
                response.setReason("账号在别处登录");
                response.setMessage("repeatCollection");
                session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
                return;
            }
            userManager.enterGameLobby(user.getUserId(), session);
            log.info("玩家 " + user.getUsername() + " 进入游戏大厅");
        } catch (NullPointerException e){
            log.error("异常信息 {}", e.getMessage());
            MatchResponse response = new MatchResponse();
            response.setOk(false);
            response.setReason("您尚未登录");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 处理开始匹配请求和停止匹配请求
        User user = (User) session.getAttributes().get("user");
        String payload = message.getPayload();
        MatchRequest request = objectMapper.readValue(payload, MatchRequest.class);
        MatchResponse response = new MatchResponse();
        if(request.getMessage().equals("startMatch")){
            // 加入到匹配队列，返回一个响应
            matcher.add(user);
            response.setOk(true);
            response.setMessage("startMatch");
        } else if(request.getMessage().equals("stopMatch")){
            matcher.remove(user);
            response.setOk(true);
            response.setMessage("stopMatch");
        } else {
            response.setOk(false);
            response.setReason("非法匹配请求");
        }
        session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        // 玩家下线
        try {
            User user = (User) session.getAttributes().get("user");
            WebSocketSession online = userManager.getOnline(user.getUserId());
            if(online == session) {
                userManager.exitGameLobby(user.getUserId());
            }
            matcher.remove(user);
            log.info("玩家 " + user.getUsername() + " 退出游戏大厅");
        } catch (NullPointerException e) {
            log.error("异常信息: {}", e.getMessage());

        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 玩家下线
        try {
            User user = (User) session.getAttributes().get("user");
            WebSocketSession online = userManager.getOnline(user.getUserId());
            matcher.remove(user);
            if(online == session) {
                userManager.exitGameLobby(user.getUserId());
            }
            log.info("玩家 " + user.getUsername() + " 退出游戏大厅");
        } catch (NullPointerException e) {
            log.error("异常信息: {}", e.getMessage());
        }
    }
}
